package com.example.vendingmachine.service.impl;

import com.example.vendingmachine.dto.OrderDTO;
import com.example.vendingmachine.dto.OrderQuery;
import com.example.vendingmachine.dto.OrderStatsDTO;
import com.example.vendingmachine.entity.Order;
import com.example.vendingmachine.entity.Product;
import com.example.vendingmachine.entity.Slot;
import com.example.vendingmachine.mapper.OrderMapper;
import com.example.vendingmachine.service.OrderService;
import com.example.vendingmachine.service.ProductService;
import com.example.vendingmachine.service.SlotService;
import com.example.vendingmachine.exception.BusinessException;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

/**
 * 订单服务实现类
 */
@Service
@RequiredArgsConstructor
public class OrderServiceImpl implements OrderService {

    private final OrderMapper orderMapper;
    private final SlotService slotService;
    private final ProductService productService;

    @Override
    public PageInfo<Order> listOrders(OrderQuery query) {
        PageHelper.startPage(query.getPageNum(), query.getPageSize());
        return new PageInfo<>(orderMapper.selectList(query));
    }

    @Override
    public Order getOrderById(Long id) {
        Order order = orderMapper.selectById(id);
        if (order == null) {
            throw new BusinessException("订单不存在");
        }
        return order;
    }

    @Override
    public Order getOrderByOrderNo(String orderNo) {
        Order order = orderMapper.selectByOrderNo(orderNo);
        if (order == null) {
            throw new BusinessException("订单不存在");
        }
        return order;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Order createOrder(OrderDTO orderDTO) {
        // 检查货道是否存在且状态为启用
        Slot slot = slotService.getSlotById(orderDTO.getSlotId());
        if (!"ENABLED".equals(slot.getStatus())) {
            throw new BusinessException("货道已被禁用");
        }

        // 检查商品是否存在且状态为启用
        Product product = productService.getProductById(slot.getProductId());
        if (!"ENABLED".equals(product.getStatus())) {
            throw new BusinessException("商品已下架");
        }

        // 检查库存是否充足
        if (slot.getStock() < orderDTO.getQuantity()) {
            throw new BusinessException("商品库存不足");
        }

        // 创建订单
        Order order = new Order();
        order.setOrderNo(generateOrderNo());
        order.setSlotId(orderDTO.getSlotId());
        order.setProductId(slot.getProductId());
        order.setQuantity(orderDTO.getQuantity());
        order.setPrice(product.getPrice());
        order.setAmount(product.getPrice().multiply(new java.math.BigDecimal(orderDTO.getQuantity())));
        order.setPayType(orderDTO.getPayType());
        order.setStatus("PENDING");

        orderMapper.insert(order);

        // 扣减库存
        slotService.updateSlotStock(slot.getId(), slot.getStock() - orderDTO.getQuantity());

        return order;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void payOrder(Long id) {
        Order order = getOrderById(id);
        if (!"PENDING".equals(order.getStatus())) {
            throw new BusinessException("订单状态不正确");
        }

        orderMapper.updateStatus(id, "PAID", LocalDateTime.now());
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void completeOrder(Long id) {
        Order order = getOrderById(id);
        if (!"PAID".equals(order.getStatus())) {
            throw new BusinessException("订单状态不正确");
        }

        orderMapper.updateStatus(id, "COMPLETED", null);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void cancelOrder(Long id) {
        Order order = getOrderById(id);
        if (!"PENDING".equals(order.getStatus())) {
            throw new BusinessException("订单状态不正确");
        }

        orderMapper.updateStatus(id, "CANCELLED", null);

        // 恢复库存
        Slot slot = slotService.getSlotById(order.getSlotId());
        slotService.updateSlotStock(slot.getId(), slot.getStock() + order.getQuantity());
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void refundOrder(Long id) {
        Order order = getOrderById(id);
        if (!"PAID".equals(order.getStatus()) && !"COMPLETED".equals(order.getStatus())) {
            throw new BusinessException("订单状态不正确");
        }

        orderMapper.updateStatus(id, "REFUNDED", null);

        // 恢复库存
        Slot slot = slotService.getSlotById(order.getSlotId());
        slotService.updateSlotStock(slot.getId(), slot.getStock() + order.getQuantity());
    }

    @Override
    public OrderStatsDTO getOrderStats(OrderQuery query) {
        return orderMapper.selectStats(query);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateOrderStatus(Long id, String status) {
        Order order = orderMapper.selectById(id);
        if (order == null) {
            throw new BusinessException("订单不存在");
        }
        
        orderMapper.updateStatusWithoutPayTime(id, status);
    }

    /**
     * 生成订单编号
     */
    private String generateOrderNo() {
        return "VM" + DateTimeFormatter.ofPattern("yyyyMMddHHmmssSSS")
                .format(LocalDateTime.now());
    }
} 